package com.hongawen.channel;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author hongawen
 * @version 1.0
 * @data 2025/4/22 13:58
 */
@Slf4j
public class TestByteBuffer {

    /**
     * 简介：从指定的文件读取最多100字节，并打印出来
     * @param args .
     */
    public static void main(String[] args) {
        /**
         * 1、可以通过输入或者输出流读取fileChannel
         * 2、RandomAccessFile也可以获取fileChannel
         */
        String filePath = System.getProperty("user.dir") + "/io/data.txt";
        try (FileChannel fileChannel = new FileInputStream(filePath).getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(100);
            // 切换为读取模式
            int read = fileChannel.read(buffer);
            System.out.println("未切换读模式时，直接读取position的位置值为：" + buffer.get());
            StringBuffer sb = new StringBuffer();
            while (read != -1) {
//                System.out.println("read = " + read);
//                System.out.println("limit = " + buffer.limit());
//                System.out.println("position = " + buffer.position());
                buffer.flip();
                buffer.rewind();
                while (buffer.hasRemaining()) {
                    byte b = buffer.get();
                    sb.append((char) b);
//                    System.out.println("读后的position = " + buffer.position());
                }
                buffer.clear();
                read = fileChannel.read(buffer);
            }
            log.info("{}", sb);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
